package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.adapter.MyOnScroll;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.BusinessBean;
import com.example.administrator.szb.bean.MyXMBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by D N on 2017/10/27.
 */


public class MyXMActivity extends BaseActivity {
    @Bind(R.id.my_xm_recyclerview)
    RecyclerView myXmRecyclerview;

    MyXMBean myXMBean;
    BusinessBean businessBean;
    @Bind(R.id.myxm_swiperefreshlayout)
    SwipeRefreshLayout myxmSwiperefreshlayout;
    private int current_page = 1;
    private int per_page = 10;
    Map<Integer, MyXMBean.YWInfoData> s;//
    BaseAdapter<MyXMBean.DataBean.BBean> adapter;
    ArrayList<MyXMBean.DataBean.BBean> mdata = new ArrayList<>();
    View footerview;

    View error_head;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_xm_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        initToolbar(R.id.my_xm_toolbar_include, "我的项目");
        /**
         * todo 项目列表
         */
        footerview = LayoutInflater.from(this).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        initView();

    }

    private void initView() {
        initRefreshLayout();
       // initRecyclerview();
    }
    /**
     * 开启刷新监听
     */
    private void initRefreshLayout() {
        myxmSwiperefreshlayout.setColorSchemeResources(R.color.zhutise);
        myxmSwiperefreshlayout.post(new Runnable() {
            @Override
            public void run() {
                current_page = 1;
                myxmSwiperefreshlayout.setRefreshing(true);
                requestXMList(0);
            }
        });

        myxmSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                current_page = 1;
                myxmSwiperefreshlayout.setRefreshing(true);
                requestXMList(0);
            }
        });
    }

    private void requestXMList(final int isRefreshOrMore) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("current_page", "" + current_page);
        map.put("per_page", "" + per_page);

        HttpUtils.post2(activity,URLAddress.URLBASE + URLAddress.URL_XM, map, 0, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {

                try {
                    myXMBean = JSON.parseObject(str,new TypeReference<MyXMBean>(){});
                } catch (Exception e) {
                    str = str.replace("\"indentInfo\":[]","\"indentInfo\":null");
                    str = str.replace("\"a\":null","\"a\":[]");
                    str = str.replace("\"b\":null","\"b\":[]");
                    myXMBean = JSON.parseObject(str,new TypeReference<MyXMBean>(){});
                }
                if (myXMBean.getResult() == 1) {
                    if (isRefreshOrMore == 0) {
                        mdata.clear();
                        if (myXMBean.getData().getB()==null){

                        }
                        mdata.addAll(myXMBean.getData().getB());
                        myxmSwiperefreshlayout.setRefreshing(false);
                        current_page = current_page+1;
                        // Toasts.show(getActivity(), "刷新成功", Toast.LENGTH_SHORT);
                    }else if(isRefreshOrMore == 1){
                        if (myXMBean.getData().getB().size()>0){
                            current_page = current_page+1;
                            mdata.addAll(myXMBean.getData().getB());
                        }else{
                            Toasts.show(MyXMActivity.this, "没有数据了", Toast.LENGTH_SHORT);
                        }


                        footerview.setVisibility(View.INVISIBLE);
                    }
                    initRecyclerview();
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(int requestCode, String str) {

                myxmSwiperefreshlayout.setRefreshing(false);
            }
        });


        //businessBean = WecomeActivity.businessBean;


    }

    private void initRecyclerview() {

        myXmRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseAdapter<MyXMBean.DataBean.BBean>(this, mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, MyXMBean.DataBean.BBean dataBean) {
                ((TextView) holder.getView(R.id.textView144)).setText(dataBean.getBusinessName());
                ((TextView) holder.getView(R.id.textView148)).setText(dataBean.getStatus());
                HashMap<Integer, MyXMBean.YWInfoData> map = (HashMap<Integer, MyXMBean.YWInfoData>) dataBean.getIndentInfo();
                String info = "";
                for (int i = 0; i < dataBean.getBusformId().size(); i++) {
                    info = info + map.get(dataBean.getBusformId().get(i)).getKeyName() + ":" + map.get(dataBean.getBusformId().get(i)).getValueName() + "     ";
                }
                ((TextView) holder.getView(R.id.textView149)).setText(info);
                if (dataBean.getBusformId().size() == 0){
                    ((TextView) holder.getView(R.id.textView149)).setText("联系人："+dataBean.getName());
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                Log.e("pdf", "getLayoutId: " + viewType);
                return R.layout.view_my_xmxq_userinfo;
            }
        };
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                /**
                 * todo 传入订单状态
                 */
                Intent intent = new Intent(MyXMActivity.this, XMXQActivity_my.class);
               // intent.putExtra("statu", position);
                intent.putExtra("dd_id",mdata.get(position).getId());
                intent.putExtra("genre",1);
                startActivity(intent);
            }
        });

        if (mdata.size() == 0){
            error_head = LayoutInflater.from(MyXMActivity.this).inflate(R.layout.view_item_error, myXmRecyclerview, false);
            ((TextView)error_head.findViewById(R.id.text_view_error)).setText("您尚未发布项目哦");
            adapter.addHeaderView(error_head);
            //messageViewShow.setVisibility(View.GONE);
        }else{
            adapter.addFootView(footerview);
            loadMore();//开启加载更多监听
        }


        myXmRecyclerview.setAdapter(adapter);

    }

    /**
     * 开启加载更多
     */
    private void loadMore() {

        myXmRecyclerview.addOnScrollListener(new MyOnScroll(){
            @Override
            public void scrollBottom() {
                if (!myxmSwiperefreshlayout.isRefreshing()) {//如果在刷新状态就不再加载更多了！否则会触发两次srollBottom()方法！
                    super.scrollBottom();
                    footerview.setVisibility(View.VISIBLE);
                    requestXMList(1);
                }

            }
        });
    }
}
